package com.itheima.transaction;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-10 09:29
 * @description 就是让写环绕的
 */
public class TransactionInterceptor implements MethodInterceptor {

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {

        Object result=null;
        try {
            //开启事务
            transactionManager.begin();


            //调用原来业务service代码
            result = methodInvocation.proceed();


            //提交事务
            transactionManager.commit();
        }catch (Throwable e){
            //回滚事务
            transactionManager.rollback();

            //异常处理
            throw e;
        }finally {
            //关闭资源
            transactionManager.close();
        }
        return result;

    }
}
